<!--数据回显-->
<!--1.提交数据报错后,将刚才提交的数据回显到表单中-->
<!--2.编辑数据的时候,取消编辑还原旧数据-->

<template>
  <section>

    <el-dialog
        title="导入员工"
        :visible.sync="impVisible"
        width="30%"
        :before-close="handleClose">

      <span>上传文件:</span>
        <el-upload
          class="upload-demo"
          action=""
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="6"
          :on-exceed="handleExceed"
          :file-list="fileList">
        <el-button  size="small" type="primary" >上传</el-button>
        <div slot="tip" class="el-upload__tip">欢迎上传员工信息</div>
      </el-upload>

      <span slot="footer" class="dialog-footer">
    <el-button @click="impVisible = false">取 消</el-button>

    <el-button  type="primary" @click="impVisible = false;open()" >确 定</el-button>

  </span>
    </el-dialog>


    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">

        <el-form-item>
          <el-input v-model="filters.findname" placeholder="员工名称"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" v-on:click="findOrExport">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd()">新增</el-button>
        </el-form-item>

<!--        导入导出-->
        <el-form-item>
<!--        <el-upload :action="'http://'+serverIp+':8081/emp/import'"-->
<!--        :show-file-list="true"-->
<!--                   accept="xlsx"-->
<!--                   :multiple="true"-->
<!--                   :on-success="handleExcelImportSuccess">-->
<!--        </el-upload>-->
          <el-button type="primary" @click="impVisible = true">导入<i class="el-icon-bottom"></i></el-button>

        </el-form-item>


        <el-form-item>
        <el-button type="primary" id="1" v-on:click="findOrExport($event)" >
          导出<i class="el-icon-top"></i>
        </el-button>
        </el-form-item>
<!--        ********************************************-->
<!--        ********************************************-->
      </el-form>
    </el-col>


    <!--列表-->
    <el-table :data="pageInfo" highlight-current-row  @selection-change="selsChange" style="width: 100%;">
      <!--      选框-->
      <el-table-column type="selection" width="55">
      </el-table-column>

      <el-table-column type="index" width="60">
      </el-table-column>

      <!--      列表-->
      <!--      :formatter="formatStatus"-->
      <el-table-column prop="username" label="用户名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="200" sortable>
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="150" sortable>
        <template v-slot="scope">
          <img :src="scope.row.headImage" width="75">
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="120" sortable>
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门" min-width="180" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template v-slot="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--批删和分页-->
    <!--    page-size:每页显示条目个数-->
    <!--    page-sizes:每页显示个数选项器-->
    <!--    :disabled="this.sels.length === 0" 如果没有数据让删除按钮失效 -->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemoveEmps" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          layout="total, sizes,prev, pager, next,jumper"
          @current-change="handleCurrentChange"

          :page-size="query.pageSize"
          :page-sizes="[5,10,15,20,30]"
          :total="pageInfo.total"
          :current-page="query.currentPage"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--****************************************************************************-->
    <!--*****************************新增和编辑界面***********************************-->
    <!--****************************************************************************-->
    <!--
    :visible.sync  控制dialog是否显示
     :rules  绑定表单校验规则
     prop:绑定校验规则的名称
   -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="su"><!-- ref给表单取别名 -->
        <el-form-item label="员工名" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="headImage">
          <el-input v-model="saveForm.headImage" auto-complete="off"></el-input>
        </el-form-item>

        <!--        ****************************************  -->
        <!--      ****************编辑新增--下拉框****************  -->
        <!--        ****************************************  -->
        <!--数据类型不匹配会发生400错误-->
        <el-form-item label="所属部门" >
          <!--          <el-input v-model="saveForm.manager_id" auto-complete="off"></el-input>-->
          <!--          value-key:绑定为对象-->
          <el-select v-model="saveForm.department" value-key="id" placeholder="选择">
            <el-option v-for=" dept in options"
                       :key="dept.id"
                       :label="dept.name"
                       :value="dept">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--****************************************************************************-->
    <!--****************************************************************************-->
    <!--****************************************************************************-->

  </section>
</template>

<script>
import {addEmp, batchRemoveEmps, findDepts,getEmpList, removeEmp} from "../../api/api";
import xlsx, {utils, writeFile} from "xlsx";

export default {
  name: "Employee",
  // data为初始化页面值
  data() {
    return {
      success:false,
      msg:"",
      impVisible:false,
      // addFileTitleName: "员工导入",
      // serverIp:"127.0.0.1",
      empForm:{
        id:null,
        username:null,
        password:null,
        headImage:null,
        age:null,
        email:null,
        department_id:null,
        department:null,
      },

      pageInfo: {
        // 总条数
        total: 0,
        rows: []
      },

      //初始化分页
      query: {
        //当前页码
        currentPage: 1,
        //每页显示条数
        pageSize: 10
      },
      /***************************************/

      //高级查询名字
      filters: {
        findname: '',
      },

      sels: [],//列表选中列，批删

      /***************************************************************/
      /******************初始化新增和编辑方法****************************/
      /***************************************************************/
      saveFormVisible: false,//新增界面是否显示
      saveLoading: false,
      options: [],
      title: "新增或修改员工",
      // 表单校验规则
      //trigger:blur---失去焦点时触发验证
      saveFormRules: {
        username: [
          {required: true, message: '请输入员工名字', trigger: 'blur'}
        ]
      },

//新增界面数据
      saveForm: {
        id:null,
        username:null,
        password:null,
        headImage:null,
        age:null,
        email:null,
        department_id:null,
        department:null,
      },

      //下拉员工初始化数据
      employees: [],

      //父级部门树
      deptTree: [],

      // 显示新增
      //显示新增界面
      handleAdd() {
        this.saveForm = {
          id:null,
          username:null,
          password:null,
          headImage:null,
          age:null,
          email:null,
          department_id:null,
          department:null,
        }
        this.saveFormVisible = true
        this.loadDepts()
      },

      //显示编辑界面,需要做数据回显
      //把row行中的数据拷贝到表单中去
      handleEdit(index, row) {
        Object.assign(this.saveForm, row)
        this.saveFormVisible = true;
        this.loadDepts()
      },

      /**************************************************************/
      /*************************删除*********************************/
      /**************************************************************/
      //index:当前数据的行号
      //row:当前行数据
      handleDel(index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          //NProgress.start();
          let para = {id: row.id}
          removeEmp(para).then((res) => {
            this.listLoading = false
            //NProgress.done();
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getEmployee()
          });
        }).catch(() => {

        });
      },



      // **************************************************
      // **************************************************
      // **************************************************
    }


  },


  methods: {


    //列表更改
    selsChange(sels) {
      this.sels = sels
    },


    //提交弹出框
    //$refs代表所有ref:取了别名的
    saveSubmit() {
      this.$refs.su.validate((valid) => {
        if (valid) {
          this.$confirm('确定提交么?', '提示', {}).then(() => {
            this.saveLoading = true
            addEmp(this.saveForm).then((res) => {
              if (res.data.success) {
                this.$message({
                  message: '成功',
                  type: 'success'
                })
              } else {
                this.$message.error(res.data.message)
              }
              this.getEmployee()
              this.saveLoading = false
              this.saveFormVisible = false
            })
          })
        }
      })
    },

    //高级查询或者导出
    findOrExport(index) {

      let way = index.currentTarget.id

      if(way==1){
        this.exportEmployee(this.filters.findname)
      }
      if(way=="") {
        this.query.currentPage = 1
        this.getEmployee()
      }
    },

    //js方法
    //账号状态转换
    // formatStatus: function (row, column) {
    // 	return row.state == 1 ? '正常' : row.state == 0 ? '停用' : '未知';
    // },

    //当前页码改变时触发
    handleCurrentChange(currentPage) {
      this.query.currentPage = currentPage
      this.getEmployee()
    },

    //页码大小改变时触发(success)
    handleSizeChange(pageSize) {
      this.query.pageSize = pageSize
      this.getEmployee()
    },

    //获取员工列表
    getEmployee() {
      this.listLoading = true
      //封装数据
      let query = {
        //this调用的是data里面的初始化数据
        currentPage: this.query.currentPage,
        pageSize: this.query.pageSize,
        key: this.filters.findname
      }
      // this.$http.post("/dept",query)
      getEmpList(query).then(res => {
      //res.data.data返回数据需要嵌套一层
        res = res.data
        this.pageInfo = res.data

        // 总数
        this.pageInfo.total = res.count
        //关闭加载
        this.listLoading = false
      }).catch(result => {
        this.$message({message: '分页查询失败', type: 'error'});
      })
    },

    //获取所有员工
    //下拉框
    loadDepts() {
      findDepts().then((res) => {
        this.options = res.data

      })
    },



    // **************************************************//
    // *********************批删*************************//
    // **************************************************//


    //批量删除
    batchRemoveEmps() {
      //箭头函数相当于function函数简写
      //去掉function,改成箭头=>
      //形参小括号写到箭头左边
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        //NProgress.start();
        //前端直接给的是数组
        // let para = {ids: ids}

        batchRemoveEmps(ids).then((res) => {

          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getEmployee()
        });
      }).catch(() => {

      });
    },

    //高级导出员工
    exportEmployee(findname){
      //let是固定值,var声明后可变
      // 封装数据
      var exp = {exportname : findname}
      if(findname != ""){
        this.$http.post("/emp/export",exp).then(res => {
          const jsonData = res.data.data
          const headDisplay = {
            username :"用户名",
            password:"密码",
            email:"邮箱",
            headImage:"头像",
            age:"年龄",
            departmentname:"部门名"
          }
          const newData = [headDisplay,...jsonData]
          const worksheet = utils.json_to_sheet(newData,{skipHeader:true});
          const workbook = utils.book_new();
          utils.book_append_sheet(workbook, worksheet, 'Sheet1');

          writeFile(workbook, '员工信息表-指导.xlsx', { type: 'blob', bookType: 'xlsx' });

        }).catch(result => {
          this.$message({message: '导出失败', type: 'error'});
        })
      }

      if(findname == ""){
        this.$http.post("/emp/export",exp).then(res => {
            //可以是后台返回的json数据或者自己定义的值
           const jsonData = res.data.data

          //   [
          //   { name: 'John', age: 30 },
          //   { name: 'Jane', age: 28 },
          //   { name: 'Bob', age: 35 }
          //   ]
          /* 有两种设立表头的方法 */
          // const head = ["用户名","密码","邮箱","头像","年龄","部门名"]
          const headDisplay = {
            username :"用户名",
            password:"密码",
            email:"邮箱",
            headImage:"头像",
            age:"年龄",
            departmentname:"部门名"
        }
      //...代表输出[{},{},{}]数组
          const newData = [headDisplay,...jsonData]
          const worksheet = utils.json_to_sheet(newData,{skipHeader:true});
          const workbook = utils.book_new();
          utils.book_append_sheet(workbook, worksheet, 'Sheet1');

          writeFile(workbook, '员工信息表-全导.xlsx', { type: 'blob', bookType: 'xlsx' });

        }).catch(result => {
          this.$message({message: '导出失败', type: 'error'});
        })
      }
    },

    handleExcelImportSuccess(){
      this.$message.success("导入成功")
      this.load()
    },
    open(){

    }
  },
  //页面加载时
  //要注意mounted位置
  mounted() {
    this.getEmployee()

  }
}
</script>

<style scoped>

</style>